import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/match/detail/zq_match_lineup_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/match_zq_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_first_team_view.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/ads_label.dart';

class ZqLineupView extends StatefulWidget {
  const ZqLineupView({super.key, this.isSuspend});

  final bool? isSuspend;

  @override
  State<ZqLineupView> createState() => _ZqLineupViewState();
}

class _ZqLineupViewState extends State<ZqLineupView>
    with AutomaticKeepAliveClientMixin {
  final logic = Get.put(ZqMatchLineupLogic());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<ZqMatchLineupLogic>(builder: (_) {
      return Container(
        color: Colours.greyF2F3F7,
        child: ListView(padding: EdgeInsets.zero, children: [
          const AdsLabel(
            adsTag: "match_zq_阵容",
            tapType: 'ggw_bsxq_zr',
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
          ),
          if (widget.isSuspend != true) _formPadding(child: shoufa()),
          if (logic.data?.homeBackup.hasValue == true ||
              logic.data?.guestBackup.hasValue == true)
            _formPadding(child: _backup()),
          // if (logic.data?.homeSuspend.hasValue == true ||
          //     logic.data?.guestSuspend.hasValue == true)
          _formPadding(child: _suspend()),
          Container(height: 60)
        ]),
      );
    });
  }

  Widget shoufa() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                      width: 24, Utils.getImgPath("match_lineup_first.png")),
                  Container(width: 2),
                  const QsText('首发阵容',
                      fontSize: 16, fontWeight: FontWeight.w500),
                ],
              ),
              Container(
                width: 112,
                decoration: BoxDecoration(
                    color: Colours.greyF7,
                    borderRadius: BorderRadius.circular(33.5)),
                child: Stack(children: [
                  AnimatedAlign(
                      curve: Curves.fastOutSlowIn,
                      duration: const Duration(milliseconds: 300),
                      alignment: logic.select == 0
                          ? Alignment.centerLeft
                          : Alignment.centerRight,
                      child: Container(
                          width: 56,
                          height: 24,
                          decoration: BoxDecoration(
                              color: Colours.main,
                              borderRadius: BorderRadius.circular(33.5)))),
                  Row(
                    children: [
                      Container(
                        alignment: Alignment.center,
                        width: 56,
                        height: 24,
                        child: QsText("上场",
                            fontSize: 12,
                            color: logic.select == 0
                                ? Colours.white
                                : Colours.grey66),
                      ).tap(() => logic.lineupChoice(0)),
                      Container(
                        alignment: Alignment.center,
                        width: 56,
                        height: 24,
                        child: QsText("本场",
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                            color: logic.select == 1
                                ? Colours.white
                                : Colours.grey66),
                      ).tap(() => logic.lineupChoice(1)),
                    ],
                  )
                ]),
              )
            ],
          ),
        ),
        LoadingWidget<bool>(
            isLoading: logic.isLoading,
            data: logic.data?.homeLineup.hasValue != true ||
                logic.data?.guestLineup.hasValue != true,
            noData: const Padding(
              padding: EdgeInsets.symmetric(vertical: 20),
              child: NoDataWidget(),
            ),
            loading: Container(),
            child: () => const ZqFirstTeamView()),
        _iconWidget(),
      ],
    );
  }

  Widget _iconWidget() {
    return Container(
      height: 80,
      color: Colours.white,
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(
                  5,
                  (index) => Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Image.asset(
                              width: 16,
                              Utils.getImgPath(ZqLineupUtils.icon[index])),
                          const SizedBox(width: 5),
                          QsText(ZqLineupUtils.title[index],
                              fontSize: 12, height: 1, color: Colours.grey66)
                        ],
                      ))),
          Container(height: 10),
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(
                  4,
                  (index) => Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Image.asset(
                              width: 16,
                              Utils.getImgPath(ZqLineupUtils.icon[5 + index])),
                          const SizedBox(width: 5),
                          QsText(ZqLineupUtils.title[5 + index],
                              fontSize: 12, height: 1, color: Colours.grey66)
                        ],
                      ))),
        ],
      ),
    );
  }

  Widget _backup() {
    return Container(
      padding: const EdgeInsets.only(top: 16),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Padding(
          padding: const EdgeInsets.only(left: 12),
          child: Row(
            children: [
              Image.asset(
                  width: 24, Utils.getImgPath("match_lineup_backup.png")),
              const SizedBox(width: 2),
              const QsText('替补席', fontSize: 16, fontWeight: FontWeight.w500),
            ],
          ),
        ),
        const SizedBox(height: 10),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Flexible(child: backupTeam(isHome: true)),
            const SizedBox(width: 8),
            Flexible(
              child: backupTeam(isHome: false),
            ),
          ],
        ),
      ]),
    );
  }

  Widget backupTeam({required bool isHome}) {
    return Column(children: [
      Container(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
        child: Row(
          children: [
            CachedNetworkImage(
                width: 28,
                height: 28,
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (
                  context,
                  url,
                  error,
                ) =>
                    Image.asset(Utils.getImgPath("zq_placeholder.png")),
                imageUrl: isHome
                    ? logic.detail.info?.baseInfo?.homeLogo ?? ""
                    : logic.detail.info?.baseInfo?.guestLogo ?? ""),
            Container(width: 8),
            Expanded(
              child: QsText(
                  isHome
                      ? logic.detail.info?.baseInfo?.homeName ?? ""
                      : logic.detail.info?.baseInfo?.guestName ?? "",
                  fontWeight: FontWeight.w500,
                  maxLines: 2),
            )
          ],
        ),
      ),
      (isHome && logic.data?.homeBackup?.length == 0) ||
              (!isHome && logic.data?.guestBackup?.length == 0)
          ? const Padding(
              padding: EdgeInsets.symmetric(vertical: 18),
              child: QsText('暂无数据', fontSize: 11, color: Colours.grey66))
          : Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: List.generate(
                    isHome
                        ? logic.data?.homeBackup?.length ?? 0
                        : logic.data?.guestBackup?.length ?? 0,
                    (index) => backupPlayer(isHome, index)),
              ),
            )
    ]);
  }

  Widget backupPlayer(bool isHome, int index) {
    final player = isHome
        ? logic.data!.homeBackup![index]
        : logic.data!.guestBackup![index];
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        if (logic.playerEvents?[player.playerId] == null) {
          Toast.text("该球员本场未上场，暂无技术统计");
        } else {
          if (logic.data?.isLastLineup == true) {
            Get.toNamed(Routes.zqDataDialog, arguments: <int>[
              isHome
                  ? (logic.data?.homeQxbMatchId ?? 0)
                  : (logic.data?.guestQxbMatchId ?? 0),
              int.parse(player.playerId ?? "0")
            ]);
          } else {
            Get.toNamed(Routes.zqDataDialog, arguments: <int>[
              logic.data?.matchId ?? 0,
              int.parse(player.playerId ?? "0")
            ]);
          }
        }
      },
      child: Container(
        padding: const EdgeInsets.only(bottom: 8, top: 8),
        child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
          Padding(
            padding: const EdgeInsets.only(top: 2.0),
            child: Container(
                width: 28,
                height: 28,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                        width: 1.5,
                        color:
                            isHome ? Colours.homeColorRed : Colours.blue2766D6),
                    color: isHome ? Colours.homeColorRed : Colours.blue2766D6),
                child: ClipOval(
                  child: CachedNetworkImage(
                    width: 28,
                    height: 28,
                    fit: BoxFit.cover,
                    imageUrl: player.playerLogo ?? "",
                    placeholder: (context, url) => Styles.placeholderIcon(),
                    errorWidget: (context, url, error) => Container(
                      alignment: Alignment.center,
                      child: QsText(
                        '${player.number}',
                        color: Colours.white,
                        fontWeight: FontWeight.w500,
                        fontFamily: "Din",
                      ),
                    ),
                  ),
                )),
          ),
          const SizedBox(width: 4),
          Expanded(
            flex: 2,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                QsText(
                  (player.nameCn ?? player.nameEn) ?? '',
                  fontSize: 12,
                  maxLines: 1,
                  height: 1.4,
                  fontWeight: FontWeight.w500,
                ),
                if (!player.rating.noValue || player.positionName.hasValue)
                  Row(
                    children: [
                      QsText(player.positionName ?? '',
                          fontSize: 10, height: 1.4, color: Colours.grey66),
                      Container(width: 4),
                      if (!player.rating.noValue)
                        Container(
                          width: 25,
                          height: 12,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: isHome
                                  ? Colours.redEC8C81
                                  : Colours.blue81A8EC),
                          child: QsText(player.rating!,
                              needCenter: true,
                              color: Colours.white,
                              fontSize: 8),
                        )
                    ],
                  )
              ],
            ),
          ),
          if (logic.playerEvents != null &&
              logic.playerEvents?[player.playerId] != null)
            Expanded(
              flex: 1,
              child: Padding(
                padding: const EdgeInsets.only(top: 3.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(right: 3),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          ///上下场
                          _playerFlag(player.playerId, 0),
                          logic.playerEvents?[player.playerId]?[1].length != 0
                              ? Padding(
                                  padding: const EdgeInsets.only(left: 2),
                                  child: QsText(
                                      "${logic.playerEvents?[player.playerId]?[1]}'",
                                      fontSize: 11,
                                      color: Colours.grey66))
                              : Container()
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 3, right: 3),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          ///红黄牌
                          _playerFlag(player.playerId, 2),

                          ///进球点球乌龙
                          _playerFlag(player.playerId, 3),

                          ///失点
                          _playerFlag(player.playerId, 4),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
        ]),
      ),
    );
  }

  Widget _suspend() {
    return Container(
      color: Colours.white,
      padding: const EdgeInsets.only(top: 12),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Padding(
          padding: const EdgeInsets.only(left: 12),
          child: Row(
            children: [
              Image.asset(
                  width: 24, Utils.getImgPath("match_lineup_suspend.png")),
              Container(width: 2),
              const QsText('伤病及禁赛球员',
                  fontSize: 16, fontWeight: FontWeight.w500),
            ],
          ),
        ),
        const SizedBox(height: 10),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Flexible(child: _suspendList(isHome: true)),
            const SizedBox(width: 8),
            Flexible(child: _suspendList(isHome: false))
          ],
        ),
      ]),
    );
  }

  Widget _suspendList({required bool isHome}) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
          child: Row(
            children: [
              CachedNetworkImage(
                  width: 28,
                  height: 28,
                  placeholder: (context, url) => Styles.placeholderIcon(),
                  errorWidget: (
                    context,
                    url,
                    error,
                  ) =>
                      Image.asset(Utils.getImgPath("zq_placeholder.png")),
                  imageUrl: isHome
                      ? logic.detail.info?.baseInfo?.homeLogo ?? ""
                      : logic.detail.info?.baseInfo?.guestLogo ?? ""),
              Container(width: 8),
              Expanded(
                child: QsText(
                    isHome
                        ? logic.detail.info?.baseInfo?.homeName ?? ""
                        : logic.detail.info?.baseInfo?.guestName ?? "",
                    fontWeight: FontWeight.w500,
                    maxLines: 2),
              )
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: (isHome
                  // ignore: prefer_is_empty
                  ? (logic.nowData?[logic.select]?.homeSuspend?.length == 0 ||
                      logic.nowData?[logic.select]?.homeSuspend == null)
                  // ignore: prefer_is_empty
                  : (logic.nowData?[logic.select]?.guestSuspend?.length == 0 ||
                      logic.nowData?[logic.select]?.guestSuspend == null))
              ? const Padding(
                  padding: EdgeInsets.symmetric(vertical: 16),
                  child: QsText('暂无数据', fontSize: 11, color: Colours.grey66))
              : Column(
                  children: List.generate(
                      isHome == true
                          ? logic.nowData![logic.select]!.homeSuspend!.length
                          : logic.nowData![logic.select]!.guestSuspend!.length,
                      (index) => _suspendPlayer(isHome, index)),
                ),
        ),
      ],
    );
  }

  Widget _suspendPlayer(bool isHome, int index) {
    final player = isHome
        ? logic.nowData![logic.select]!.homeSuspend![index]
        : logic.nowData![logic.select]!.guestSuspend![index];
    var reasonImage = '';
    if (player.kind == 0 || player.kind == 1 || player.kind == 2) {
      reasonImage = 'icon_jinsai.png';
    } else if (player.kind != 99) {
      reasonImage = 'icon_shangbing.png';
    }
    return Container(
      padding: const EdgeInsets.only(bottom: 12, top: 8),
      child: Row(children: [
        Container(
            width: 28,
            height: 28,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                    width: 1.5,
                    color: isHome ? Colours.homeColorRed : Colours.blue2766D6),
                color: isHome ? Colours.homeColorRed : Colours.blue2766D6),
            child: ClipOval(
              child: CachedNetworkImage(
                width: 28,
                height: 28,
                fit: BoxFit.cover,
                imageUrl: player.photo ?? "",
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (context, url, error) => Container(
                  alignment: Alignment.center,
                  child: QsText(
                    '${player.number}',
                    color: Colours.white,
                    fontWeight: FontWeight.w500,
                    fontFamily: "Din",
                  ),
                ),
              ),
            )),
        const SizedBox(width: 4),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Flexible(
                    fit: FlexFit.loose,
                    child: QsText(
                      (player.nameChs) ?? '',
                      fontSize: 12,
                      maxLines: 1,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(width: 4),
                  if (reasonImage.isNotEmpty)
                    Image.asset(width: 12, Utils.getImgPath(reasonImage))
                ],
              ),
              QsText('${player.position ?? ''} ${player.reason ?? ''}',
                  fontSize: 10, color: Colours.grey99)
            ],
          ),
        )
      ]),
    );
  }

  Widget _formPadding({required Widget child}) {
    return Container(
        margin: const EdgeInsets.only(top: 8, left: 8, right: 8),
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
            color: Colours.white,
            boxShadow: [
              BoxShadow(
                  color: const Color(0xFF0F499F).withOpacity(0.04),
                  blurRadius: 12,
                  offset: const Offset(0, 2)),
            ],
            borderRadius: BorderRadius.circular(8)),
        child: child);
  }

  Widget _playerFlag(String? playerId, int index) {
    return logic.playerEvents != null &&
            logic.playerEvents?[playerId]?[index].length != 0 &&
            logic.playerEvents?[playerId] != null
        ? Container(
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(width: 0.5, color: Colours.white)),
            child: Image.asset(
                width: 12,
                height: 12,
                Utils.getImgPath(ZqLineupUtils.icon[ZqLineupUtils.title
                    .indexOf(logic.playerEvents?[playerId]?[index].trim())])))
        : Container();
  }

  @override
  bool get wantKeepAlive => true;
}
